package com.tao.basegreendaomanager

import android.content.Context
import org.greenrobot.greendao.AbstractDaoMaster
import org.greenrobot.greendao.AbstractDaoSession
import org.greenrobot.greendao.database.Database
import org.greenrobot.greendao.database.DatabaseOpenHelper

/**
 * reate by tao on{DATE}
 */
abstract class BaseGreendaoManager1<M : AbstractDaoMaster, S : AbstractDaoSession, H : DatabaseOpenHelper> {
    
    lateinit var context: Context
    private val daoSession: MutableMap<String, S> = mutableMapOf()

    fun initGreendao(context: Context, configArray: Array<DbConfig>) {
        this.context = context
        for (dbConfig in configArray) {
            addDaosession(dbConfig)
        }
    }

    fun addDaosession(dbConfig: DbConfig) {
        addDaosession(dbConfig.dbName, dbConfig.dbPassword, dbConfig.dbEntityClass)
    }

    fun addDaosession(dbName: String, password: String, classs: Array<Class<*>>) {
        if (daoSession.containsKey(dbName)) {
            return
        }
        val devOpenHelper = myGreenDaoDevHelper(dbName, classs)
        val daoMaster = daoMaster(dbName,
            if (password.isNullOrEmpty()) devOpenHelper.writableDb else devOpenHelper.getEncryptedWritableDb(
                password
            )
        )
        daoSession[dbName] = newSession(dbName,daoMaster)
    }

     open fun newSession(dbName: String, daoMaster: M): S{
        return daoMaster.newSession() as S
    }

    abstract  fun daoMaster(
        dbName: String,
        database: Database
    ): M 

    abstract fun myGreenDaoDevHelper(
        dbName: String,
        classs: Array<Class<*>>
    ): H

    fun getDaoSession(dbName: String): S? {
        return daoSession[dbName]
    }

    class DbConfig {
        constructor(dbName: String, dbPassword: String, dbEntityClass: Array<Class<*>>) {
            this.dbName = dbName
            this.dbEntityClass = dbEntityClass
            this.dbPassword = dbPassword
        }

        constructor (dbName: String, dbEntityClass: Array<Class<*>>) {
            this.dbName = dbName
            this.dbEntityClass = dbEntityClass
        }

        var dbName = ""
        var dbEntityClass = arrayOf<Class<*>>()
        var dbPassword = ""
    }


}